using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using SqlSugar;
using System.Web.Http;
using wnet.admin.dbhelper;
using wnet.admin.Models;
using System;
using Models;
using wnet.admin.Models.dto;
using wnet.admin.wentcommon;
using System.Collections.Generic;
using System.Web.UI.WebControls.WebParts;
using System.Linq;
using wnet.admin.Comm;
using wnet.admin.CommQueue;
using System.Web.Optimization;


namespace wnet.admin.Controllers.ywBusiness
{
    /// <summary>
    /// 大数据屏
    /// </summary>
    //[TokenAuth]
    [Route("ywbusiness/bigdatav3/{action}")]
    public class bigdatav3Controller : ApiController
    {

        private readonly ISqlSugarClient _sqlSugarClient;
        public bigdatav3Controller()
        {
            _sqlSugarClient = SqlSugarConfig.CreateClient();
        }

        /// <summary>
        /// 账户管理-列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost]
        public object getsysuserlist(sys_menuQueryDto parm)
        {
            if (parm == null)
            {
                parm = new sys_menuQueryDto();
            }

            var predicate = Expressionable.Create<sys_user>();
            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.name), it => it.name.Contains(parm.name));
            predicate = predicate.AndIF(parm.status != null, it => it.status == parm.status);
            var query = _sqlSugarClient.Queryable<sys_user>()
                .Where(predicate.ToExpression())
                .Select((u) => new sys_user
                {
                    id = u.id.SelectAll(),

                });

            var datalist = query.ToPage(parm);

            var data = new { code = 200, msg = "成功", data = datalist };

            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }





        /// <summary>
        /// 设备管理-列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost]
        public object getequipmentlist(yw_equipmentQueryDto parm)
        {

            var predicate = Expressionable.Create<yw_equipment>();

            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.typename), it => it.typename.Contains(parm.typename));
            if (parm.states == 3)
            {
                var startTime = DateTime.Now.Date.AddDays(-30); // 获取30天前当天的开始时间
                predicate = predicate.And(it => it.states == 1 && it.jianxiutime > startTime);
            }
            else
            {
                predicate = predicate.AndIF(parm.states != null && parm.states != 0, it => it.states == parm.states);
            }


            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.title), it => it.title.Contains(parm.title));
            var query = _sqlSugarClient.Queryable<yw_equipment>()
                .Where(predicate.ToExpression())
                .OrderByDescending(q => q.id)
                .Select((u) => new yw_equipment
                {
                    id = u.id.SelectAll(),

                });

            var datalist = query.ToPage(parm);

            var data = new { code = 200, msg = "成功", data = datalist };

            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }

     


        /// <summary>
        /// 设置设备id
        /// </summary>
        /// <param name="equid">设备id</param>
        /// <returns></returns>
        [HttpGet]
        public object setEquipmentConfig(string equid)
        {
            var data = new
            {
                code = 200,
                msg = "成功",
                data = equid
            };
            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }

        /// <summary>
        /// 根据省市区获取信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public object getequlistbyarea(string province = "", string city = "", string area = "")
        {
            //LogHelper.WriteLog("哈哈哈");

            List<object> syslist = new List<object>();
            yw_equipmentQueryDto parm = new yw_equipmentQueryDto();
            var predicate = Expressionable.Create<yw_equipment>();


            if (!string.IsNullOrWhiteSpace(province))
            {

                predicate = predicate.And(it => it.province.Contains(province));
            }
            if (!string.IsNullOrWhiteSpace(city))
            {

                predicate = predicate.And(it => it.city.Contains(city));
            }
            if (!string.IsNullOrWhiteSpace(area))
            {

                predicate = predicate.And(it => it.area.Contains(area));
            }



            var query = _sqlSugarClient.Queryable<yw_equipment>()
                .Where(predicate.ToExpression())
                .OrderByDescending(q => q.id)
                .Select((u) => new yw_equipment
                {
                    id = u.id.SelectAll(),

                });

            var datalist = query.ToPage(parm);

            foreach (var d in datalist.Result)
            {

                string statestext = "";
                if (d.states == 0)
                {
                    statestext = "正常";
                }
                if (d.states == 1)
                {
                    statestext = "维修中";
                }
                if (d.states == 2)
                {
                    statestext = "报废";
                }
                if (d.jianxiutime > DateTime.Now.AddDays(-30))
                {
                    statestext = "带检修";

                }

                syslist.Add(new { name = d.title, equid = d.id, installtime = d.installtime.Value.ToString("yyyy-MM-dd"), states = statestext });
            }


            var data = new
            {
                code = 200,
                msg = "成功",
                data = syslist
            };

            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }

        /// <summary>
        /// 切换设备数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public object getequlist()
        {
            //LogHelper.WriteLog("哈哈哈");

            List<object> syslist = new List<object>();
            syslist.Add(new { name = "设备1", equid = 1 });
            syslist.Add(new { name = "设备11", equid = 2 });
            syslist.Add(new { name = "设备12", equid = 3 });
            syslist.Add(new { name = "设备13", equid = 4 });

            var data = new
            {
                code = 200,
                msg = "成功",
                data = syslist
            };

            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }
        /// <summary>
        /// 探伤列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public object getalarmdatalist(int equid = 0)
        {
            //LogHelper.WriteLog("哈哈哈");

            var dlist = ConstDefine.mAlarmViews;
            var data = new
            {
                code = 200,
                msg = "成功",
                data = dlist
            };

            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }


        /// <summary>
        /// 大数据屏首页数据
        /// </summary>
        /// <param name="equid">设备id</param>
        /// <returns></returns>
        [HttpGet]
        public object getbighomedata(int equid = 0)
        {

            Dictionary<string, object> bigdata = new Dictionary<string, object>();
            List<object> syslist = new List<object>();

            var zgcount = _sqlSugarClient.Queryable<sys_user>().Where(q => q.status == 1).Count();
            var allcount = _sqlSugarClient.Queryable<sys_user>().Count();
            syslist.Add(new { name = "总数", value = $"{allcount}个", vkey = "userlist" });
            syslist.Add(new { name = "在岗", value = $"{zgcount}个", vkey = "zaiganglist" });
            syslist.Add(new { name = "总数", value = "34个", vkey = "userlis1t" });
            syslist.Add(new { name = "在用", value = "54个", vkey = "userli2st" });



            bigdata.Add("systemoverview", syslist);//系统概况 


            getreportdata(bigdata);//报表分析

            getreportdatashouming(bigdata);
            getyearchartdata(bigdata);//年度分析饼图

            List<object> equstatusdatalist = new List<object>();

            var quelist = WConstDefine.yw_deviceOnlineList;
            foreach (var item in quelist)
            {
                equstatusdatalist.Add(new { name = item.Name, value = item.OnLine ? "在线" : "离线" });
            }

            bigdata.Add("equstatusdata", equstatusdatalist);//设备状态 
            List<object> flawdetectiondatalist = new List<object>();

            var eqcount = _sqlSugarClient.Queryable<yw_equipment>().Count();
            var eqcount1 = _sqlSugarClient.Queryable<yw_equipment>().Where(it => it.states == 1).Count();
            var eqcount2 = _sqlSugarClient.Queryable<yw_equipment>().Where(it => it.states == 2).Count();

            var startTime = DateTime.Now.Date.AddDays(-30); // 获取30天前当天的开始时间
            var eqcount3 = _sqlSugarClient.Queryable<yw_equipment>().Where(o => o.states == 1 && o.jianxiutime >= startTime).Count();
            flawdetectiondatalist.Add(new { name = "设备信息", value = eqcount, vkey = "0" });
            flawdetectiondatalist.Add(new { name = "在用", value = eqcount1, vkey = "1" });
            flawdetectiondatalist.Add(new { name = "报废", value = eqcount2, vkey = "2" });
            flawdetectiondatalist.Add(new { name = "报修", value = eqcount3, vkey = "3" });
            bigdata.Add("flawdetectiondata", flawdetectiondatalist);//探伤数据

            getnddatafenxi(bigdata);//年度数据分析

            gethourdata(bigdata);//小时分析

            var data = new
            {
                code = 200,
                msg = "成功",
                data = bigdata
            };

            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }

        private void getnddatafenxi(Dictionary<string, object> bigdata)
        {
            List<object> nddatalist = new List<object>();



            // 指定要统计的年份
            int targetYear = DateTime.Today.Year; // 默认为当前年份

            // 查询一天内不同等级的数据量
            var levelCounts = _sqlSugarClient.Queryable<yw_llarmlist>()
                              .Where(x => x.createtime.Year == targetYear)
                                .GroupBy(x => x.damagelevel)
                                .Select(g => new AlarmRecorddto
                                {
                                    DamageLevel = g.damagelevel,
                                    Count = SqlFunc.AggregateCount(g.id)
                                })
                                .ToList();

            var possibleLevels = new[] { "等级1", "等级2", "等级3" }; // 可以根据实际情况添加更多等级

            // 创建一个包含所有等级及其数量的结果集，默认数量为0

            var result = possibleLevels.ToDictionary(
                level => level,
                level => levelCounts.FirstOrDefault(lc => lc.DamageLevel == level)?.Count ?? 0
            );

            // 构建报告数据列表
            List<object> reportDataList = new List<object>
        {
            new { name = "1", value = GetLevelCount(result, "等级1") },
            new { name = "2", value = GetLevelCount(result, "等级2") },
            new { name = "3", value = GetLevelCount(result, "等级3") },

        };

            bigdata.Add("nddatafenxi", reportDataList);//年度数据分析
        }

        /// <summary>
        /// 年度分析饼图
        /// </summary>
        /// <param name="bigdata"></param>
        void getyearchartdata(Dictionary<string, object> bigdata)
        {
            var listarm = _sqlSugarClient.Queryable<yw_llarmlist>().OrderByDescending(q => q.Area).Take(3).ToList();

            List<object> yeardatalist = new List<object>();
            List<object> yearareadatalist = new List<object>();

            if (listarm.Count > 0)
            {
                yearareadatalist.Add(new { name = "损伤面积", value = listarm[0].Area });
                yeardatalist.Add(new { name = "一", value = listarm[0].Area });
            }
            else
            {
                yearareadatalist.Add(new { name = "损伤面积", value = 0 });
                yeardatalist.Add(new { name = "一", value = 0 });
            }
            if (listarm.Count > 1)
            {
                yearareadatalist.Add(new { name = "损伤面积", value = listarm[1].Area });
                yeardatalist.Add(new { name = "一", value = listarm[1].Area });
            }
            else
            {
                yearareadatalist.Add(new { name = "损伤面积", value = 0 });
                yeardatalist.Add(new { name = "一", value = 0 });
            }
            if (listarm.Count > 2)
            {
                yearareadatalist.Add(new { name = "损伤面积", value = listarm[2].Area });
                yeardatalist.Add(new { name = "一", value = listarm[2].Area });
            }
            else
            {
                yearareadatalist.Add(new { name = "损伤面积", value = 0 });
                yeardatalist.Add(new { name = "一", value = 0 });
            }







            bigdata.Add("yearareadata", yearareadatalist);//年度分析面积 

            bigdata.Add("yearchartdata", yeardatalist);//年度分析饼图 
        }

        //小时分析
        private void gethourdata(Dictionary<string, object> bigdata)
        {
            List<object> hourfenxilist = new List<object>();


            Dictionary<string, object> dic = new Dictionary<string, object>();


            // 获取当前时间并舍入到最近的整点
            var now = DateTime.Now;
            var startTime = now.AddHours(-10).Date.AddHours(now.AddHours(-10).Hour);
            var endTime = now.Date.AddHours(now.Hour);

            var hourlyCounts = Enumerable.Range(0, 10)
                .Select(offset =>
                {
                    var hourStart = startTime.AddHours(offset);
                    var hourEnd = hourStart.AddHours(1);

                    // 查询该小时内的记录数量
                    var count = _sqlSugarClient.Queryable<yw_llarmlist>()
                                  .Where(x => x.createtime >= hourStart && x.createtime < hourEnd)
                                  .Count();

                    return new
                    {
                        Hour = hourStart.ToString("HH"),
                        Count = count
                    };
                }).ToList();


            int[] data1 = hourlyCounts.Select(item => item.Count).ToArray();
            dic.Add("xAxis", hourlyCounts.Select(item => item.Hour).ToArray());



            List<object> ylist = new List<object>();
            ylist.Add(new { name = "设备A", data = data1 });
            var data2 = new[] { 120,
                132,
                101,
                134,
                90,
                230,
                210,500,100,120};
            ylist.Add(new { name = "设备2", data = data2 });
            dic.Add("yAxis", ylist);


            dic.Add("maxnum", data1.Max(q => q));
            dic.Add("newnum", data1[data1.Length - 1]);


            bigdata.Add("hourfenxidata", dic);//小时分析
        }

        private void getreportdata(Dictionary<string, object> bigdata)
        {
            var eqcount = _sqlSugarClient.Queryable<yw_wirerope>().Count();
            var eqcount1 = _sqlSugarClient.Queryable<yw_wirerope>().Where(it => it.states == 1).Count();
            var eqcount2 = _sqlSugarClient.Queryable<yw_wirerope>().Where(it => it.states == 2).Count();

            var startTime = DateTime.Now.Date.AddDays(-30); // 获取30天前当天的开始时间
            var eqcount3 = _sqlSugarClient.Queryable<yw_wirerope>().Where(o => o.states == 1 && o.jianxiutime >= startTime).Count();
            // 构建报告数据列表
            List<object> reportDataList = new List<object>();

            reportDataList.Add(new { name = "轻微", value = eqcount, vkey = "0" });
            reportDataList.Add(new { name = "一般", value = eqcount1, vkey = "1" });
            reportDataList.Add(new { name = "严重", value = eqcount2, vkey = "2" });
            reportDataList.Add(new { name = "致命", value = eqcount3, vkey = "3" });

            bigdata.Add("reportdata", reportDataList);//报表分析 
        }
        /// <summary>
        /// 钢丝绳全寿命期损伤统计信息
        /// </summary>
        /// <param name="bigdata"></param>
        private void getreportdatashouming(Dictionary<string, object> bigdata)
        {
            var eqcount = _sqlSugarClient.Queryable<yw_wirerope>().Count();
            var eqcount1 = _sqlSugarClient.Queryable<yw_wirerope>().Where(it => it.states == 1).Count();
            var eqcount2 = _sqlSugarClient.Queryable<yw_wirerope>().Where(it => it.states == 2).Count();

            var startTime = DateTime.Now.Date.AddDays(-30); // 获取30天前当天的开始时间
            var eqcount3 = _sqlSugarClient.Queryable<yw_wirerope>().Where(o => o.states == 1 && o.jianxiutime >= startTime).Count();
            // 构建报告数据列表
            List<object> reportDataList = new List<object>();

            reportDataList.Add(new { name = "磨损", value = eqcount, vkey = "0" });
            reportDataList.Add(new { name = "断丝", value = eqcount1, vkey = "1" });
            reportDataList.Add(new { name = "锈蚀", value = eqcount2, vkey = "2" });
            reportDataList.Add(new { name = "变形", value = eqcount3, vkey = "3" });

            bigdata.Add("reportdatashouming", reportDataList);//报表分析 
        }
        // 辅助方法：从字典获取指定等级的数量，如果不存在则返回0
        private static int GetLevelCount(Dictionary<string, int> dictionary, string level)
        {
            if (dictionary.TryGetValue(level, out int count))
            {
                return count;
            }
            return 0;
        }


        /// <summary>
        /// 首页统计 --小时伤痕趋势图
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        [HttpGet]
        object getstatisticsscar(string day = "")
        {



            string sqlstr = @"SELECT strftime('%H', alarmdate) AS hour, COUNT(*) AS num
FROM yw_llarmlist
WHERE alarmdate >= DATETIME('2024-11-04', '-24 hours')
GROUP BY hour
ORDER BY hour;";
            sqlstr = @"SELECT 
    HOUR(alarmdate) as `hour`,
    COUNT(*) as `num`
FROM 
    yw_llarmlist
WHERE 
    alarmdate > NOW() - INTERVAL 24 HOUR
GROUP BY 
    HOUR(alarmdate)
		ORDER BY   HOUR(alarmdate)";
            var dlist = _sqlSugarClient.Ado.SqlQuery<sqlscardto>(sqlstr);
            foreach (var d in dlist)
            {
                d.hournum = Convert.ToInt32(d.hour) + 1;
            }

            var data = new
            {
                code = 200,
                msg = "成功",
                data = dlist.Take(10),

            };

            return Json(data, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }


    }
}